//
//  NetworkTools.swift
//  01MicroBlog
//
//  Created by Apple on 15/7/30.
//  Copyright © 2015年 heima. All rights reserved.
//

import UIKit
import AFNetworking

// 定义网络错误枚举
private let WJErrorDomainName:String = "com.heima"
/// 网络回调类型别名
typealias WJNetFinishedCallBack = (result: [String: AnyObject]?, error: NSError?)->()

private enum WJNetworkError:Int {
    case emptyDataError = -1
    case emptyTokenError = -2

    private var description:String {
        switch self {
        case .emptyDataError:
            return "空数据"
        case .emptyTokenError:
            return "AccessToken错误"
        }
    }
    private var error:NSError {
        return NSError(domain: WJErrorDomainName, code: rawValue, userInfo: [WJErrorDomainName:description])
    }
}

class NetworkTools: AFHTTPSessionManager {

    // 设置一个全局的访问点
    static let sharedNetworkTools:NetworkTools = {
        
        let url = NSURL(string: "https://api.weibo.com")
        let sharedNetworkTools = NetworkTools(baseURL: url, sessionConfiguration: NSURLSessionConfiguration.defaultSessionConfiguration())
        sharedNetworkTools.responseSerializer.acceptableContentTypes = NSSet(objects: "application/json", "text/json", "text/javascript", "text/plain","text/html") as Set<NSObject>
        
        return sharedNetworkTools
    }()

    private var clientid = "1759876144"
    private var AppSecret = "b0eecbe82c8180a8162d5622449cf779"
    
//    private var clientid = "3763573571"
//    private var AppSecret = "d3e7a54be3676c0d067f252fa5d47c07"
    
    var redirecturi = "http://www.baidu.com"
    
    // MARK:拿到授权码
    func getUrlStr() -> String {
        
        return "https://api.weibo.com/oauth2/authorize?client_id=\(clientid)&redirect_uri=\(redirecturi)"
    }
    
    /// 网络访问方法
     enum WJNetworkMethod: String {
        case GET = "GET"
        case POST = "POST"
    }
    
    
    // POST请求
    // MARK:拿到访问令牌
    func loadAccessToken(code:String, finished:WJNetFinishedCallBack) {
        
        // 准备基本的url
        let baseUrl = "https://api.weibo.com/oauth2/access_token"
        
        // 准备post参数
        let parameters = ["client_id":clientid,
                          "client_secret":AppSecret,
                          "grant_type":"authorization_code",
                          "code":code,
                          "redirect_uri":redirecturi]
        request(WJNetworkMethod.POST, urlString: baseUrl, params: parameters, finished: finished)
    }
    
    // MARK: - 发微博
    func sendStatus(status:String, image:UIImage?, finished:WJNetFinishedCallBack?) {
        
        print(image)
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished!(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据")
                
                finished!(result: nil, error: WJNetworkError.emptyDataError.error)
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished!(result: nil, error: error)
        }

        
        let userAccount = UserAccount.sharedAccount
        
        // 判断token是否存在
        if userAccount!.access_token == nil {
            return
        }
        let access_token = userAccount!.access_token!
        let url = "2/statuses/update.json"
        let parameters:[String:AnyObject] = ["access_token":access_token, "status":status]
        
        
        
        if image == nil {
            
            // 发送POST请求
            request(WJNetworkMethod.POST, urlString:url, params: parameters, finished:finished!)
            
        } else {
            let url = "2/statuses/upload.json"
            // 利用表单数据发送请求
            // 2. 构造数据体
            /**
            name: 服务器要求的字段名
            fileName: 保存在服务器的文件名，提示：如果接口文档没有指定文件名参数，可以随便写
            mimeType: 告诉服务器上传文件的类型，如果不想告诉服务器，可以使用 application/octet-stream
            格式：大类/小类
            常见的格式：
            image/png
            image/jpg
            image/gif
            text/html
            text/plain
            */

            POST(url, parameters: parameters, constructingBodyWithBlock: { (formData) -> Void in
                let data = UIImagePNGRepresentation(image!)
                print(data?.length)
                formData.appendPartWithFileData(data, name: "pic", fileName: "xxx", mimeType: "application/octet-stream")
                }, success:successCallBack , failure: failedCallBack)
            
        }
 
    }
    
    
    // get 请求
    // 加载用户信息
    func loadUserInfo(uid:String, status:WJNetFinishedCallBack?) {
        let userAccount = UserAccount.sharedAccount
        
        // 判断token是否存在
        if userAccount!.access_token == nil {
            return
        }
        let access_token = userAccount!.access_token!
        
        // 账户存在的情况下，准备发送get请求
        let url = "2/users/show.json"
        let parameters:[String:AnyObject] = ["access_token":access_token, "uid":uid]
        
        // 发送get请求
        request(WJNetworkMethod.GET, urlString:url, params: parameters, finished:status!)
        
    }
    
    // 加载微博数据
    func loadStatuses(since_id: Int, max_id:Int, finished:WJNetFinishedCallBack) {
        
        let access_token = UserAccount.sharedAccount?.access_token
        
        if access_token == nil {
           print(WJNetworkError.emptyTokenError.error)
            return
        }
        let url = "2/statuses/home_timeline.json"
//        let params:[String: AnyObject] = ["access_token":access_token!]
        var params:[String: AnyObject] = ["access_token":access_token!]
        
        if since_id > 0 {
            params["since_id"] = since_id
        }
        if max_id > 0 {
            params["max_id"] = max_id - 1
        }
        
        request(WJNetworkMethod.GET, urlString: url, params: params, finished: finished)
        
    }

    // since_id int64
    // max_id int64
 
    // MARK: - 封装 AFN 网络方法，便于替换网络访问方法，第三方框架的网络代码全部集中在此
    /// AFN 网络请求 GET / POST
    ///
    /// :param: method    HTTP 方法 GET / POST
    /// :param: urlString URL 字符串
    /// :param: params    字典参数
    /// :param: finished  完成回调
     func request(method: WJNetworkMethod, urlString: String, params: [String: AnyObject], finished: WJNetFinishedCallBack) {
        
        // 1. 定义成功的闭包
        let successCallBack: (NSURLSessionDataTask!, AnyObject!) -> Void = { (_, JSON) -> Void in
            
            if let result = JSON as? [String: AnyObject] {
                // 有结果的回调
                finished(result: result, error: nil)
            } else {
                // 没有错误，同时没有结果
                print("没有数据 \(method) Request \(urlString)")
                
                finished(result: nil, error: WJNetworkError.emptyDataError.error)
            }
        }
        
        // 2. 定义失败的闭包
        let failedCallBack: (NSURLSessionDataTask!, NSError!) -> Void = { (_, error) -> Void in
            print(error)
            
            finished(result: nil, error: error)
        }
        
        // 3. 根据 method 来选择执行的方法
        switch method {
        case .GET:
            GET(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        case .POST:
            POST(urlString, parameters: params, success: successCallBack, failure: failedCallBack)
        }
    }

    
}

